import axios, { type Method } from 'axios'
import { useUserStore } from '../stores/user'
const service = axios.create({
  baseURL: 'https://api-hmzs.itheima.net/tj',
  timeout: 20 * 1000,
})
export interface ResponseType<T> {
  code: number
  msg: string
  data: T
}
export const request = <T>(url: string, method: Method = 'GET', data?: Object) => {
  return service.request<T, ResponseType<T>>({
    url,
    method,
    [method.toUpperCase() === 'GET' ? 'params' : 'data']: data
  })
}
service.interceptors.request.use(
  config => {
    const store = useUserStore()
    if (store.token) {
      config.headers.Authorization = `Bearer ${store.token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  },
)

service.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    return Promise.reject(error)
  },
)

export default service
